package com.ducbt.model;

import java.util.ArrayList;

import com.ducbt.databasehelper.FileDatabaseHelper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class ListFileDatabase {
	private SQLiteDatabase database;
	private FileDatabaseHelper dbHelper;
	private String[] allColumns = { FileDatabaseHelper.COLUMN_ID,
			FileDatabaseHelper.COLUMN_FILENAME, 
			FileDatabaseHelper.COLUMN_CHECK,
			FileDatabaseHelper.COLUMN_TITLE};
	public ListFileDatabase(Context context) {
		dbHelper = new FileDatabaseHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}
	
	public boolean createRecord(ListFileDTO listmoc) {
		ContentValues values = new ContentValues();
		values.put(FileDatabaseHelper.COLUMN_FILENAME, listmoc.getFileName());
		values.put(FileDatabaseHelper.COLUMN_CHECK, (listmoc.isCheck()==true)?1:0);
		values.put(FileDatabaseHelper.COLUMN_TITLE, listmoc.getTitle());
		long insertId = database.insert(FileDatabaseHelper.TABLE_NAME, null,
				values);
//		Cursor cursor = database.query(FileDatabaseHelper.TABLE_NAME,
//				allColumns, FileDatabaseHelper.COLUMN_ID + " = " + insertId, null,
//				null, null, null);
//		cursor.moveToFirst();
//		ListFileDTO newRecord = cursorToObject(cursor);//
//		cursor.close();
		if(insertId == -1){
			return false;
		}
		return true;
	}
	
	public ArrayList<ListFileDTO> getAllRecords() {
		ArrayList<ListFileDTO> listFiles = new ArrayList<ListFileDTO>();

		Cursor cursor = database.query(FileDatabaseHelper.TABLE_NAME,
				allColumns, null, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			ListFileDTO listFile = cursorToObject(cursor);
			listFiles.add(listFile);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return listFiles;
	}
	
	private ListFileDTO cursorToObject(Cursor cursor) {
		ListFileDTO listFile = new ListFileDTO();
		listFile.setID(cursor.getInt(0));
		listFile.setFileName(cursor.getString(1));
		listFile.setCheck("1".equals(cursor.getString(2))?true:false);
		listFile.setTitle(cursor.getString(3));
		return listFile;
	}
	
}
